import React from "react";
import {selector, useRecoilValue,atom, useRecoilState} from "recoil";

const defaultList = atom({
    key: 'originList',
    default: [
        {
            id: 'xxxxx',
            value: '默认数据',
            isComplete: false
        }
    ]
})
const getAsyncData = selector({
    key: 'asyncList',
    get: async ({get}) => {
        return await getList();
    },
});

async function getList() {
    return fetch('/mock/todoList.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (myJson) {
            console.log(myJson);
            return myJson;
        })
}

export default function AsyncDemo() {
    const [list, setList] = useRecoilState(defaultList)
    const asyncList  = useRecoilValue(getAsyncData);

    return (<div>
        <button type="button" className="btn btn-primary" onClick={() => setList(asyncList)}>加载异步数据数据</button>
        <ul>
            {
                list.map(item => {
                    return <li key={item.id}>{item.value}</li>
                })
            }
        </ul>
    </div>)

}
